package com.bawei.movie

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.common.mvi.BaseMviFragment
import com.bawei.http.HttpManager
import com.bawei.movie.adapter.MovieListAdapter
import com.bawei.movie.api.MovieApiServer
import com.bawei.movie.databinding.FragmentMovieListBinding
import com.bawei.common.entity.MovieEntity
import com.bawei.movie.repos.MovieRepository
import com.bawei.movie.viewmodel.MovieViewModel
import com.bumptech.glide.Glide
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MovieListFragment : BaseMviFragment<FragmentMovieListBinding>() {

    private val mViewModel: MovieViewModel by lazy {
        MovieViewModel(MovieRepository(HttpManager.instance.getRetrofit().create(MovieApiServer::class.java)))
    }
    private var movieList = mutableListOf<MovieEntity>()
    private lateinit var mMovieAdapter: MovieListAdapter
    private lateinit var mRecyclerView: RecyclerView

    private var typeId: Int = -1
    private var pageIndex: Int = 1
    private var pageSize: Int = 10

    companion object {
        @JvmStatic
        fun newInstance(tabId: Int) =
            MovieListFragment().apply {
                arguments = Bundle().apply {
                    putInt("tabId", tabId)
                }
            }
    }

    override fun getLayoutId(): Int = R.layout.fragment_movie_list

    override fun initViews() {
        //获取视频类型参数
        arguments?.let {
            typeId = it.getInt("tabId")
        }

        //初始化RecyclerView
        mRecyclerView = mDataBinding.rvMovie
        //默认ItemView缓存大小为2, 数值越大缓存的Item就越多，占用内存就越大
        mRecyclerView.setItemViewCacheSize(10)
        mRecyclerView.setHasFixedSize(true) //Item布局大小为固定大小

        //适当调整缓存池大小, 默认缓存池的大小为5
        var pool = RecyclerView.RecycledViewPool()
        pool.setMaxRecycledViews(0, 5)
        mRecyclerView.setRecycledViewPool(pool)

        //根据RecyclerView的滚动事件来暂停或恢复加载
        mRecyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(this@MovieListFragment).resumeRequests() //恢复图片加载
                } else {
                    Glide.with(this@MovieListFragment).pauseRequests() //暂停图片加载
                }
            }
        })

        //取消不需要的Item动画
        (mRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

        //下拉刷新
        mDataBinding.refreshLayout.setOnRefreshListener {
            if(it.isRefreshing){
               it.finishRefresh()
            }
            pageIndex = 1
            refreshOrMoreList()
        }

        //初始化recyclerview
        mDataBinding.rvMovie.layoutManager = GridLayoutManager(requireContext(), 2, GridLayoutManager.VERTICAL, false)
        mMovieAdapter = MovieListAdapter(movieList).apply {
            preloadItemCount = 4
            onPreload = {
                pageIndex += 1
                refreshOrMoreList()
            }
        }

        //设置Item点击事件
        mMovieAdapter.setOnItemClickListener(object: MovieListAdapter.OnItemClickListener{
            override fun onItemChildClick(v: View?, position: Int) {
                ARouter.getInstance().build("/detail/activity").withSerializable("movieEntity", movieList[position]).navigation()
            }
        })

        mRecyclerView.swapAdapter(mMovieAdapter, true)
    }

    override suspend fun collectUIState() {
        mViewModel.uiState.collect{
            when(it){
                is MovieUiState.LoadMovieListSuccess -> {
                    mDataBinding.refreshLayout.finishRefresh()
                    if(pageIndex == 1){
                        movieList.clear()
                    }
                    movieList.addAll(it.list)
                    mMovieAdapter.notifyDataSetChanged()
                }
                is MovieUiState.LoadMovieListFail -> {
                    movieList.clear()
                    mMovieAdapter.notifyDataSetChanged()
                    //重置页面ID, 防止页数不断增加
                    if (pageIndex > 1) {
                        pageIndex -= 1
                    }
                }
                else -> {}
            }
        }
    }

    /**
     * 对外暴露更新数据的方法
     */
    fun updateData(id: Int){
        typeId = id
        pageIndex = 1
        refreshOrMoreList()
    }

     private fun refreshOrMoreList(){
        lifecycleScope.launch {
            //推荐
            if(typeId == -1){
                mViewModel.channel.send(MovieViewIntent.LoadRecommendMovieList(pageIndex, pageSize))
            }
            //分类
            else {
                mViewModel.channel.send(MovieViewIntent.LoadMovieList(typeId, pageIndex, pageSize))
            }
        }
    }
}